/*
 * Copyright 2009 Cedric Priscal
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.vanzo.talkie;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.XmlResourceParser;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;

import com.vanzo.bean.Channel;
import com.vanzo.bean.ChannelDaoUtil;
import com.vanzo.talkie2.R;
import com.vanzo.util.LogUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android_serialport_api.SerialPort;

public class Application extends android.app.Application {

    private static final String TAG = "Application";
    private static final String DEFAULT_DEVICE_PATH = "/dev/ttyMT0";
    private static final String SHARED_PREFERENCE = "talkie_share";
    private static final String HAS_INIT_FORM_XML = "has_init_form_xml";
    private static final String DEFAULT_CHANNELS_FILE_NAME = "default_channels_file.xml";
    private static final String USED_ID = "used_id";
    private static final String WORK_MODE = "work_mode";
    private static final String POWER_MODE = "power_mode";
    private static final String GBW_MODE = "gbw_mode";
    private static final String TFV_DEFAULT = "tfv_default";
    private static final String RFV_DEFAULT = "rfv_default";
    private static final String TX_DEFAULT = "tx_default";
    private static final String RX_DEFAULT = "rx_default";
    private static final String SQ_DEFAULT = "rx_default";
    private static final String VOLUME_DEFAULT = "volume_default";
    private SerialPort mSerialPort = null;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private ChannelDaoUtil channelDaoUtil;

    private List<Channel> channels;
    private int work_mode;
    private boolean power_mode;
    private boolean gbw_mode;
    private String volume_level;

    private Channel defaultChannel;
    private Long usedId;


    public SerialPort getSerialPort(String devicePath, int baudrate) throws SecurityException, IOException, InvalidParameterException {
        if (mSerialPort == null) {
            String path;
            if (devicePath == null || devicePath.isEmpty()) {
                path = "/dev/ttyMT0";
            } else {
                path = devicePath;
            }

			/* Check parameters */
            if ((path.length() == 0) || (baudrate == -1)) {
                throw new InvalidParameterException();
            }

			/* Open the serial port */
            mSerialPort = new SerialPort(new File(path), baudrate, 0);
            LogUtil.put(this, "device path = " + devicePath + " | baudrate = " + baudrate, LogUtil.WARN);
        }
        return mSerialPort;
    }

    public void closeSerialPort() {
        if (mSerialPort != null) {
            mSerialPort.close();
            mSerialPort = null;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        channelDaoUtil = new ChannelDaoUtil(this);
        sharedPreferences = getSharedPreferences(SHARED_PREFERENCE, Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
        initChannels();
    }

    private void initChannels() {
        if (!sharedPreferences.getBoolean(HAS_INIT_FORM_XML, false)) {
            try {
                channels = initChannelsFromXML();
                editor.putBoolean(HAS_INIT_FORM_XML, true).apply();
                channelDaoUtil.insertMultChannel(channels);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            LogUtil.put(this, "init Channels from db start", LogUtil.DEBUG);
            channels = channelDaoUtil.queryAllChannel();
        }
        String default_channel_tfv = sharedPreferences.getString(TFV_DEFAULT, "409.7500");
        String default_channel_rfv = sharedPreferences.getString(RFV_DEFAULT, "409.7500");
        String default_channel_tx = sharedPreferences.getString(TX_DEFAULT, "39");
        String default_channel_rx = sharedPreferences.getString(RX_DEFAULT, "39");
        String default_channel_sq = sharedPreferences.getString(SQ_DEFAULT, "0");


        defaultChannel = new Channel(null, "新标题", default_channel_tfv, default_channel_rfv, default_channel_tx, default_channel_rx, default_channel_sq);
        work_mode = sharedPreferences.getInt(WORK_MODE, 0);
        gbw_mode = sharedPreferences.getBoolean(GBW_MODE, false);
        power_mode = sharedPreferences.getBoolean(POWER_MODE, false);
        volume_level = sharedPreferences.getString(VOLUME_DEFAULT, "3");
        usedId = sharedPreferences.getLong(USED_ID, 0);
    }


    private List<Channel> initChannelsFromXML() throws Exception {
        LogUtil.put(this, "init Channels from xml start", LogUtil.DEBUG);
        ChannelParser parser = new ChannelParser();
        XmlResourceParser xmlResourceParser = getResources().getXml(R.xml.default_connects);
        return parser.parse(xmlResourceParser);
    }

    public void outChannelsToXML() {
        if (channels != null) {
            ChannelParser parser = new ChannelParser();
            try {
                String xmlString = parser.serialize(channels);
                String fileName = "/sdcard/" + DEFAULT_CHANNELS_FILE_NAME;
                FileOutputStream outStream = new FileOutputStream(fileName, false);
                OutputStreamWriter writer = new OutputStreamWriter(outStream, "utf-8");
                writer.write(xmlString);
                writer.flush();
                writer.close();//记得关闭

                outStream.close();
                Toast.makeText(this, "导出至" + fileName, Toast.LENGTH_LONG).show();
                Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                scanIntent.setData(Uri.fromFile(new File(fileName)));
                this.sendBroadcast(scanIntent);
            } catch (Exception e) {
                LogUtil.put(this, "init Channels from xml start", e);
                e.printStackTrace();
            }
        }
    }

    public Channel getUsedChannel() {
        Channel channel = channelDaoUtil.queryChannelById(usedId);
        if (channel == null) {
            channel = defaultChannel;
        }
//        LogUtil.put(this, "getUsedChannel = " + channel.toString(), LogUtil.WARN);
        return channel;
    }

    public List<Channel> getChannels() {
        initChannels();
        Log.d(TAG, Arrays.toString(channels.toArray()));
        return channels;
    }

    public int getWork_mode() {
//        LogUtil.put(this, "isWork_mode = " + work_mode, LogUtil.WARN);
        return work_mode;
    }

    public void setWork_mode(int work_mode) {
//        LogUtil.put(this, "setWork_mode = " + work_mode, LogUtil.WARN);
        this.work_mode = work_mode;
        editor.putInt(WORK_MODE, work_mode).apply();
    }

    public boolean isPower_mode() {
        return power_mode;
    }

    public void setPower_mode(boolean power_mode) {
        this.power_mode = power_mode;
        editor.putBoolean(POWER_MODE, power_mode).apply();
    }

    public String getVolume_level() {
        return volume_level;
    }

    public void setVolume_level(String volume_level) {
        this.volume_level = volume_level;
        editor.putString(VOLUME_DEFAULT, volume_level).apply();
    }

    public boolean isGbw_mode() {
        return gbw_mode;
    }

    public void setGbw_mode(boolean gbw_mode) {
        this.gbw_mode = gbw_mode;
        editor.putBoolean(GBW_MODE, gbw_mode).apply();
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        closeSerialPort();
    }

    public boolean addChannel(Channel channel) {
        return channelDaoUtil.insertChannel(channel);
    }

    public Channel getChannelById(Long id) {
        return channelDaoUtil.queryChannelById(id);
    }

    public boolean updateChannel(Channel channel) {
        return channelDaoUtil.updateChannel(channel);
    }

    public void updateDefaultChannel(Channel channel) {
        this.defaultChannel = channel;
        editor.putString(TFV_DEFAULT, channel.getTfv()).
                putString(RFV_DEFAULT, channel.getRfv()).
                putString(TX_DEFAULT, channel.getTx()).
                putString(RX_DEFAULT, channel.getRx()).
                putString(SQ_DEFAULT, channel.getSq()).apply();
    }

    public boolean deleteChannel(long id) {
        Channel channel = channelDaoUtil.queryChannelById(id);
        return channelDaoUtil.deleteChannel(channel);
    }

    public int getSize() {
        return getChannels().size();
    }

    public void setUsedId(Long usedId) {
        this.usedId = usedId;
        editor.putLong(USED_ID, usedId).apply();
    }

    public Long getUsedId() {
        return usedId;
    }

}
